//
//  TTRecyclingDetailHeaderView.m
//  TaoTuo
//
//  Created by zhaoshijie on 2020/9/4.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingDetailHeaderView.h"
#import "TTDetailModel.h"
#import "TYCyclePagerView.h"
#import "TYPageControl.h"
#import "TYCyclePagerViewCell.h"
#import "YBImageBrowser.h"
#import "LLDateUtilis.h"

static NSString *bannerCellIdentifier = @"recycling_detailBannerCellIdentifier";

@interface TTRecyclingDetailHeaderView ()<TYCyclePagerViewDataSource, TYCyclePagerViewDelegate>
{
    NSInteger hour;
    NSInteger minute;
    NSInteger second;
    // 总秒数
    NSInteger totalSecond;
}

@property (nonatomic, strong) TYCyclePagerView *pagerView;
//@property (nonatomic, strong) TYPageControl *pageControl;
@property (nonatomic, strong) UILabel *countPageLabel;

@property (nonatomic, strong) UIView *timeBgView;
@property (nonatomic, strong) UIButton *timeBtn;
@property (nonatomic, strong) UILabel *priceLabel;  // 价格
@property (nonatomic, strong) UILabel *titleLabel;  // 标题
@property (nonatomic, strong) UIButton *chujiaBtn;   // 出价
@property (nonatomic, strong) UIButton *weiguanBtn;   // 围观
///立即分享按钮
@property (nonatomic, strong) UIButton *shareBtn;

/// 最下面的一条背景
@property (nonatomic, strong) UIView *bottomLineView;

@property (nonatomic, copy) NSString *btnTitlePrefix;
/// 已结束
@property (nonatomic, assign) BOOL isEnd;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation TTRecyclingDetailHeaderView

+ (instancetype)headerViewWithDetailModel:(TTRecyclingDetailModel *)model
{
    TTRecyclingDetailHeaderView *headerView = [[self alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH + 150)];
    headerView.model = model;
    return headerView;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.subject = [RACSubject subject];
        self.backgroundColor = [UIColor whiteColor];
        
        [self addPagerView];
        [self addCountPageLabel];
        [self.pagerView reloadData];

    }
    return self;
}

- (void)setModel:(TTRecyclingDetailModel *)model
{
    if (model == nil) {
        return;
    }
    _model = model;
    NSString *prefix = @"价格 ";
    if (model.SalesModel == 2) {
        prefix = @"起拍价 ";
        self.chujiaBtn.hidden = NO;
    }
    NSString *priceStr = [NSString stringWithFormat:@"%@¥%@", prefix, model.Price];
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:priceStr];
    [attr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13], NSForegroundColorAttributeName : UIColorHex(0x666666)} range:[priceStr rangeOfString:prefix]];
    [attr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:10]} range:[priceStr rangeOfString:@"¥"]];
    self.priceLabel.attributedText = attr;
    self.titleLabel.text = model.Title;
    
    NSString *chujiaStr = [NSString stringWithFormat:@" 出价%d人", model.Goods_Offer_Count];
    [self.chujiaBtn setTitle:chujiaStr forState:UIControlStateNormal];
    
    NSString *weiguanStr = [NSString stringWithFormat:@" %d人围观", model.ReadingVolume];
    [self.weiguanBtn setTitle:weiguanStr forState:UIControlStateNormal];
    
    self.countPageLabel.text = [NSString stringWithFormat:@"1/%ld", model.BannerImages.count];
    [self.pagerView reloadData];
    
    
    [self setupSubviews];
    
}

#pragma mark - TYCyclePagerViewDataSource
- (NSInteger)numberOfItemsInPagerView:(TYCyclePagerView *)pageView {
    return self.model.BannerImages.count;
}

- (UICollectionViewCell *)pagerView:(TYCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index {
    TTDetailBannerModel *bannerModel = self.model.BannerImages[index];
    TYCyclePagerViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:bannerCellIdentifier forIndex:index];
    NSString *imgUrlStr = bannerModel.FileType == 0 ? bannerModel.ImageUrl : bannerModel.VideoCoverImage;
    [cell setImageUrlString:imgUrlStr isVideo:bannerModel.FileType == 1];
    return cell;
}

- (TYCyclePagerViewLayout *)layoutForPagerView:(TYCyclePagerView *)pageView {
    TYCyclePagerViewLayout *layout = [[TYCyclePagerViewLayout alloc]init];
    layout.itemSize = CGSizeMake(pageView.width, pageView.height);
    layout.itemHorizontalCenter = YES;  // 居中显示
    layout.layoutType = TYCyclePagerTransformLayoutNormal;

    return layout;
}


- (void)pagerView:(TYCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    TTDetailBannerModel *bannerModel = self.model.BannerImages[toIndex];
    self.countPageLabel.text = [NSString stringWithFormat:@"%ld/%ld", toIndex+1, self.model.BannerImages.count];
    self.countPageLabel.hidden = bannerModel.FileType == 1;
    self.playerView.hidden = bannerModel.FileType != 1;

    if (bannerModel.FileType == 1) {
        self.playerView.frame = CGRectMake(toIndex * self.width, 0, self.width, self.width);
        self.playerView.videoUrlString = bannerModel.ImageUrl;
        self.canRotation = YES;
        [self.playerView play];

    } else {
        self.canRotation = NO;
        [self.playerView pause];
    }

    [self.subject sendNext:@(self.canRotation)];

}

- (void)pagerView:(TYCyclePagerView *)pageView didSelectedItemCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index
{
    NSLog(@"选中了 -->%ld", index);
    TYCyclePagerViewCell *tyCell = (TYCyclePagerViewCell *)cell;

    TTDetailBannerModel *bannerModel = self.model.BannerImages[index];
    if (bannerModel.FileType == 1) {
        return;
    }
    // 查看图片
    NSMutableArray *imgs = [NSMutableArray array];
    @autoreleasepool {
        for (TTDetailBannerModel *bannerModel in self.model.BannerImages) {
            NSString *imgUrlStr = bannerModel.FileType == 0 ? bannerModel.ImageUrl : bannerModel.VideoCoverImage;
            YBIBImageData *data = [YBIBImageData new];
            data.imageURL = [NSURL URLWithString:imgUrlStr];
            [imgs addObject:data];
        }
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = imgs;
        browser.currentPage = index;
        [browser show];
    }


}


// 分享
- (void)shareAction
{
    if (self.shareBlock) {
        self.shareBlock();
    }
}


- (void)handleTimeEventWithComponents:(NSDateComponents *)diff
{
    hour = diff.hour >= 0 ? diff.hour : 0;
    minute = diff.minute >= 0 ? diff.minute : 0;
    second = diff.second >= 0 ? diff.second : 0;
    // 总秒数
    totalSecond = hour * 3600 + minute * 60 + second;
    
    NSString *text = [NSString stringWithFormat:@"%@%02ld : %02ld : %02ld", _btnTitlePrefix, hour, minute, second];
    [self.timeBtn setTitle:text forState:UIControlStateNormal];
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    YYWeakProxy *proxy = [YYWeakProxy proxyWithTarget:self];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)timerAction
{
    totalSecond--;
    if (totalSecond < 0) {
        totalSecond = 0;
        self.model = self.model;
        return;
    }
    
    hour = totalSecond / 3600;
    minute = totalSecond % 3600 / 60;
    second = totalSecond % 3600 % 60;
    
    NSString *text = [NSString stringWithFormat:@"%@%02ld : %02ld : %02ld", _btnTitlePrefix, hour, minute, second];
    [self.timeBtn setTitle:text forState:UIControlStateNormal];
    
}

// 竞价的情况
- (void)handleJingJia
{
    // 获取当前时间
    NSString *currentDateStr = [LLDateUtilis getCurrentTimeString];
    // 距离开始时间差
    NSDateComponents *diff1 = [LLDateUtilis compareFromDateString:self.model.StartTime toDateString:currentDateStr deteUnit:Hour | Minute | Second];
    if (diff1.second < 0) {
        // 还未开始
        _btnTitlePrefix = @"距离开始：";
        NSDateComponents *diff = [LLDateUtilis compareFromDateString:currentDateStr toDateString:self.model.StartTime deteUnit:Hour | Minute | Second];
        [self handleTimeEventWithComponents:diff];
        
        if (self.goodsStatusBlock) {
            self.goodsStatusBlock(upcoming);
        }
        
    } else {
        _btnTitlePrefix = @"距离结束：";
        // 时间差
        NSDateComponents *diff = [LLDateUtilis compareFromDateString:currentDateStr toDateString:self.model.EndTime deteUnit:Hour | Minute | Second];
        if (diff.second <= 0) {
            // 已结束
            self.isEnd = YES;
//            self.height = SCREEN_WIDTH + 150;
            if (self.goodsStatusBlock) {
                self.goodsStatusBlock(isEnd);
            }
            return;
        } else {
            [self handleTimeEventWithComponents:diff];
            if (self.goodsStatusBlock) {
                self.goodsStatusBlock(isStart);
            }
        }
        
    }
    
//    self.height = SCREEN_WIDTH + 150 + 30;
}

- (void)setupSubviews
{

    [self.timeBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pagerView.mas_bottom);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(38);
    }];
    [self.timeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(18);
        make.centerY.equalTo(self.timeBgView);
    }];
    
    self.timeBgView.hidden = YES;
    MASViewAttribute *priceTop = self.pagerView.mas_bottom;
    if (self.model.SalesModel == 2) {
        [self handleJingJia];
        if (!self.isEnd) {
            priceTop = self.timeBgView.mas_bottom;
            self.timeBgView.hidden = NO;
        }
    }
    
    [self.priceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(priceTop).mas_offset(15);
        make.left.mas_equalTo(15);
    }];

    [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.priceLabel.mas_bottom).mas_offset(10);
        make.left.equalTo(self.priceLabel);
        make.right.equalTo(self).mas_offset(-15);
    }];

    [self.chujiaBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(10);
        make.left.equalTo(self.titleLabel);
    }];

    if (self.chujiaBtn.hidden) {
        [self.weiguanBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(10);
            make.left.equalTo(self.titleLabel);
        }];
    } else {
        [self.weiguanBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.chujiaBtn);
            make.left.equalTo(self.chujiaBtn.mas_right).mas_offset(15);
        }];
    }

    [self.shareBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.chujiaBtn);
        make.right.equalTo(self).mas_offset(0);
        make.height.mas_equalTo(21*kScale);
    }];

    [self.bottomLineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.shareBtn.mas_bottom).mas_offset(10);
        make.left.right.equalTo(self);
        make.height.equalTo(@10);
    }];
    
    [self layoutIfNeeded];

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.shareBtn.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(12.5, 12.5)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = path.CGPath;
    self.shareBtn.layer.mask = maskLayer;

    self.height = self.bottomLineView.bottom;
}

- (void)addPagerView
{
    TYCyclePagerView *pagerView = [[TYCyclePagerView alloc]init];
    pagerView.frame = CGRectMake(0, 0, self.width, self.width);
    pagerView.isInfiniteLoop = NO;
//    pagerView.autoScrollInterval = 3.0;
    pagerView.dataSource = self;
    pagerView.delegate = self;
    [pagerView registerClass:[TYCyclePagerViewCell class] forCellWithReuseIdentifier:bannerCellIdentifier];
    [self addSubview:pagerView];
    self.pagerView = pagerView;
}

- (void)addCountPageLabel
{
    _countPageLabel = [UILabel labelTextCenterWithTitle:@"" color:UIColor.whiteColor fontSize:13];
    _countPageLabel.frame = CGRectMake(self.width - 65, self.pagerView.bottom - 55, 50, 20);
    _countPageLabel.layer.cornerRadius = 10;
    _countPageLabel.layer.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4].CGColor;
    [self.pagerView addSubview:_countPageLabel];
}


- (LLPlayerContainerView *)playerView
{
    if (!_playerView) {
        _playerView = [[LLPlayerContainerView alloc] initWithFrame:self.pagerView.frame superView:self.pagerView.collectionView inViewController:self.viewController];
    }
    return _playerView;
}

- (UIView *)timeBgView
{
    if (!_timeBgView) {
        _timeBgView = [[UIView alloc] init];
        _timeBgView.backgroundColor = UIColorHex(#DF4343);
        [self addSubview:_timeBgView];
    }
    return _timeBgView;
}

- (UIButton *)timeBtn
{
    if (!_timeBtn) {
        _timeBtn = [UIButton createButtonWithTitle:@"" titleColor:UIColor.whiteColor titleFont:[UIFont systemFontOfSize:15] backgroundColor:nil target:nil action:nil];
        [_timeBtn setImage:[UIImage imageNamed:@"time_biao"] forState:UIControlStateNormal];
        [self.timeBgView addSubview:_timeBtn];
    }
    return _timeBtn;
}

- (UILabel *)priceLabel
{
    if (!_priceLabel) {
        _priceLabel = [UILabel labelWithTitle:@"" color:UIColorHex(#F22F3A) font:[UIFont boldSystemFontOfSize:24]];
        [self addSubview:_priceLabel];
    }
    return _priceLabel;
}


- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel labelWithTitle:@"" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:16]];
        _titleLabel.numberOfLines = 0;
        [self addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UIButton *)chujiaBtn
{
    if (!_chujiaBtn) {
        _chujiaBtn = [UIButton createButtonWithTitle:@"出价0人" titleColor:UIColorHex(666666) titleFont:[UIFont systemFontOfSize:12] backgroundColor:nil target:nil action:nil];
        [_chujiaBtn setImage:[UIImage imageNamed:@"chujia_chuizi"] forState:UIControlStateNormal];
        _chujiaBtn.hidden = YES;
        [self addSubview:_chujiaBtn];
    }
    return _chujiaBtn;
}

- (UIButton *)weiguanBtn
{
    if (!_weiguanBtn) {
        _weiguanBtn = [UIButton createButtonWithTitle:@"0人围观" titleColor:UIColorHex(666666) titleFont:[UIFont systemFontOfSize:12] backgroundColor:nil target:nil action:nil];
        [_weiguanBtn setImage:[UIImage imageNamed:@"weiguan"] forState:UIControlStateNormal];
        [self addSubview:_weiguanBtn];
    }
    return _weiguanBtn;
}



- (UIButton *)shareBtn
{
    if (!_shareBtn) {
        _shareBtn = [UIButton createButtonWithTitle:@"立即分享" titleColor:UIColor.whiteColor titleFont:[UIFont systemFontOfSize:11] backgroundColor:UIColorHex(#BD86FD) target:self action:@selector(shareAction)];
        [self addSubview:_shareBtn];
        _shareBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 6);
    }
    return _shareBtn;
}

- (UIView *)bottomLineView
{
    if (!_bottomLineView) {
        _bottomLineView = [[UIView alloc] init];
        _bottomLineView.backgroundColor = UIColorHex(F2F2F2);
        [self addSubview:_bottomLineView];
    }
    return _bottomLineView;
}


@end
